package com.zhongge.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhongge.entity.Student;
import com.zhongge.entity.Teacher;
import com.zhongge.service.impl.StudentServiceImpl;
import com.zhongge.vo.StudentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;


import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhongge
 * @since 2025-11-09
 */
@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentServiceImpl studentService;


    /**
     * 分页查询学生信息（包含班级名称）
     * @param page 分页参数
     * @param name 学生姓名（可选）
     * @param studentNumber 学号（可选）
     * @param classId 班级ID（可选）
     * @return 分页结果
     */
    @GetMapping("/listByClsID")
    @ResponseBody
    public Map<String, Object> getStudentList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String studentNumber,
            @RequestParam Long classId) {


        Map<String, Object> result = new HashMap<>();
        try {
            IPage<StudentVO> studentPage = studentService.getStudentPage(page, size, name, studentNumber, classId);
            result.put("success", true);
            result.put("rows", studentPage.getRecords());
            result.put("total", studentPage.getTotal());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    //分页显示数据
    @GetMapping("/listByClsIDPage")
    @ResponseBody
    public Map<String, Object> getStudentByClassID(
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "rows",defaultValue = "10") Integer size,
            @RequestParam("classId") Integer id) {


        Map<String, Object> result = new HashMap<>();
        try {
            IPage<StudentVO> studentPage = studentService.getStudentByClassID(page, size, id);
            result.put("success", true);
            result.put("rows", studentPage.getRecords());
            result.put("total", studentPage.getTotal());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    //跳转页面
    @GetMapping("/classStudents")
    public String dispatch(Integer classId, Model model){
        // ModelAndView modelAndView = new ModelAndView();
        //注意这里只能使用重定向将参数传递到前端去："redirect:/studestsys/teacher/class-students.html?classId=" + classId
        //因为前端使用的获取参数方法是用easyui的：url:'/student/list?classId='+getParameter('classId'),  // 动态获取班级ID
        //正是因为这样的一个形式，所以我们必须得使用重定向将参数传递过去

        /*该方案不可用
        modelAndView.addObject("classId",classId);
        modelAndView.setViewName("studestsys/teacher/class-students");*/

        /*方案二：也不可取 因为你已经配置不带.html了
        * 因为springboot的静态资源原因：以下的形式是找不到路径的，所以我们换与其等价的方案三*/
        //return "redirect:/studestsys/teacher/class-students.html?classId=" + classId;

        /*
        * 方案三：
        * */
        // 将classId传递给模板
        model.addAttribute("classId", classId);
        // 返回模板名称（不带.html后缀）
        return "studestsys/teacher/class-students";
    }

    //添加/修改学生信息
    @PostMapping("/save")
    @ResponseBody
    public Map<String, Object> saveOrUpdate(Student student){
        Map<String, Object> map = new HashMap<>();

        try{
            boolean save = studentService.saveOrUpdate(student);
            if (save){
                map.put("success",true);
                map.put("message","添加或者修改成功");
            }else {
                map.put("success",false);
                map.put("message","添加或者修改失败");
            }
        }catch (Exception e){
            map.put("success",false);
            map.put("message","出现异常！请重试");
        }
        return map;
    }

    //删除学生信息：根据id删除学生
    @PostMapping("/delete")
    @ResponseBody
    public Map<String, Object> deleteStu(Integer id){
        Map<String, Object> map = new HashMap<>();

        try{
            boolean b = studentService.removeById(id);
            if (b){
                map.put("success",true);
                map.put("message","删除成功");
            }else {
                map.put("success",false);
                map.put("message","删除失败");
            }
        }catch (Exception e){
            map.put("success",false);
            map.put("message","可能因为该学生关联其他数据，因此无法删除！！！");
        }
        return map;
    }

    //重置学生密码：首先根据学生id查询该学生，然后初始化密码为：stu+学号(因为学号是唯一的)
    @PostMapping("/resetPassword")
    @ResponseBody
    public Map<String, Object> resetPassword(Integer id){
        Map<String, Object> map = new HashMap<>();

        try{
            //首先查询出该学生
            Student student = studentService.getById(id);
            if (student != null){
                //进行密码的重置
                //1）获取学号
                String studentNumber = student.getStudentNumber();
                //2）重置密码
                student.setPassword("stu"+studentNumber);

                //3）奖学生保存
                boolean update = studentService.updateById(student);//注意这里是修改
                if (update){
                    map.put("success",true);
                    map.put("message","密码重置成功✔️");
                }else {
                    map.put("success",false);
                    map.put("message","密码重置失败✖️");
                }
            }else {
                map.put("success",false);
                map.put("message","没有该学生");
            }
        }catch (Exception e){
            map.put("success",false);
            map.put("message","出现异常了，请重试！！😱");
        }
        return map;
    }


    //学生登录页面验证
    @GetMapping("/login")
    @ResponseBody
    public Map<String, Object> login(@RequestParam("studentId") String studentId,
                                     @RequestParam("password") String password,
                                     HttpSession session){
        Map<String, Object> result = new HashMap<>();
        Student student = studentService.login(studentId, password);
        if (student != null) {
            //如果成功的话，就将信息存储于会话中
            session.setAttribute("LOGGED_IN_STUDENT",student);
            result.put("success", true);
        } else {
            result.put("success", false);
            result.put("message", "学号或密码错误");
        }
        return result;
    }

    //跳转学生首页
    @GetMapping("/studentIndex")
    public String studentIndex(){
        return "/studestsys/student/student-index";
    }
}
